<template>
	<page-meta :page-style="'overflow:' + (popupVisible || modalShow ? 'hidden' : 'visible')"></page-meta>

	<view class="page-container bg-grey">
		<up-navbar placeholder :auto-back="true" title="提交订单"></up-navbar>

		<view class="card-wrap">
			<view class="card ticket-info">
				<view class="display-name-wrap">
					<view class="display-name">{{ combotktData.display_name }}</view>
					<PreSaleInfo
						:sale_type="combotktData.sale_type"
						:use_date_tips="combotktData.use_date_tips"
						:use_week_tips="combotktData.use_week_tips"
						:use_time_tips="combotktData.use_time_tips"
					/>
				</view>

				<view class="prices" v-if="combotktData.sale_type === 10">
					<template v-if="combotktData.tour_date_type === 20">
						<SubmitOrderPriceList
							:id="ticketId"
							:date="date[0]"
							page_type="combotkt"
							:prices="combotktData.prices"
							:latest_sale_date="combotktData.latest_sale_date"
							@price-change="handleSinglePriceChange"
							@calendar-visible="handlePopupVisible"
						/>
					</template>
					<view v-if="combotktData.tour_date_type === 10" class="combo_sale">
						<view class="tourist-tip-info" v-if="!hasPrices">
							<image :src="`${imgBaseUrl}tourist-info-icon.png`" class="icon" />
							<text class="text">请选择游玩日期</text>
						</view>
						<view
							class="combo_sale_item"
							v-for="(item, index) in combotktData.combo_sale_infos"
							:key="index"
						>
							<view class="sku_name">{{ item.sku_name }}</view>
							<SubmitOrderPriceList
								:id="ticketId"
								:date="date[index]"
								page_type="combotkt"
								:prices="item.prices"
								:idx="index"
								:latest_sale_date="item.latest_sale_date"
								@price-change="(e) => handleMultiplePriceChange(index, e)"
								@calendar-visible="handlePopupVisible"
							/>
						</view>
					</view>
				</view>

				<view class="sale-labels-wrap">
					<SaleLabels
						:display_name="combotktData.display_name"
						:use_rule="combotktData.use_rule"
						:sale_tips="combotktData.sale_tips"
						:booking_tips="combotktData.booking_tips"
					/>
				</view>

				<view class="ops">
					<AmountOperation
						ref="amountOperationRef"
						:unit_price="pricesInfo.price_in_cent"
						@total-price-change="handleTotalPriceChange"
					/>
				</view>
			</view>

			<TouristInfo ref="touristInfoRef" :tourist_contact_rule="combotktData.tourist_contact_rule" />
			<ContactInfo ref="contactInfoRef" :tourist_contact_rule="combotktData.tourist_contact_rule" />
		</view>

		<view class="bottom">
			<view class="price">
				<text class="prefix font-oppo">¥</text>
				<text class="num font-oppo">{{ hasPrices ? priceInCent(total_price) : "--" }}</text>
			</view>
			<view class="btn" :class="{ disabled: !hasPrices }" @click="handleSubmit">立即预定</view>
		</view>

		<BookingNoticeModal :show="modalShow" :booking_notice="combotktData.booking_notice" @close="handleClose" />
	</view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue"
import { onLoad } from "@dcloudio/uni-app"
import XEUtils from "xe-utils"
import { $getCombotktDetail, $createCombotkt } from "@/api/combotkt"
import { priceInCent } from "@/mixins/mixins"
import PreSaleInfo from "../components/pre-sale-info.vue"
import SubmitOrderPriceList from "../components/submit-order-price-list.vue"
import SaleLabels from "../components/sale_labels.vue"
import AmountOperation from "../components/amount-operation.vue"
import TouristInfo from "../components/tourist-info.vue"
import ContactInfo from "../components/contact-info.vue"
import BookingNoticeModal from "../components/booking-notice-modal.vue"
const imgBaseUrl = inject("imgBaseUrl")

const date = ref([])
const ticketId = ref("")
const popupVisible = ref(false)
const modalShow = ref(false)
const combotktData = ref({})
const pricesInfo = ref({
	date: "",
	price_in_cent: "",
})
const mutiplePriceList = ref([])
const total_price = ref(0)
const amountOperationRef = ref(null)
const touristInfoRef = ref(null)
const contactInfoRef = ref(null)

const hasPrices = computed(() => {
	// 预售票
	if (combotktData.value.sale_type === 20) {
		const { salable, sold_out } = combotktData.value.prices[0]

		return salable && !sold_out
	}

	return pricesInfo.value.price_in_cent
})

const handleSinglePriceChange = (info) => (pricesInfo.value = info)
const handlePopupVisible = (visible) => (popupVisible.value = visible)
const handleTotalPriceChange = (price) => (total_price.value = price)
const handleClose = () => (modalShow.value = false)
const handleMultiplePriceChange = (index, info) => {
	mutiplePriceList.value[index] = info

	if (mutiplePriceList.value.filter(Boolean).length === combotktData.value.combo_sale_infos.length) {
		const max = mutiplePriceList.value.reduce((pre, cur) => (cur.price_in_cent > pre ? cur.price_in_cent : pre), 0)

		const item = mutiplePriceList.value.find((item) => item.price_in_cent === max)

		pricesInfo.value.date = item.date
		pricesInfo.value.price_in_cent = item.price_in_cent
	}
}

const handleSubmit = XEUtils.debounce(async () => {
	if (!hasPrices.value) return

	if (!touristInfoRef.value.touristList) {
		uni.showToast({ title: "请填写游客信息", icon: "none" })
		return
	} else {
		const diff = touristInfoRef.value.touristList.length - touristInfoRef.value.touristList.filter(Boolean).length

		if (diff > 0) {
			uni.showToast({ title: "请填写游客信息", icon: "none" })
			return
		}
	}

	if (!contactInfoRef.value.contactInfo) {
		uni.showToast({ title: "请填写联系信息", icon: "none" })
		return
	}

	const {
		contact_require_id_value,
		contact_require_mobile,
		contact_require_name,

		tourist_require_id_value,
		tourist_require_mobile,
		tourist_require_name,
	} = combotktData.value.tourist_contact_rule
	const contactInfo = contactInfoRef.value.contactInfo

	let combos = []

	// 统一选择
	if (combotktData.value.tour_date_type === 20) {
		combos = combotktData.value.combo_sale_infos.map((item) => ({
			ticket_sku_id: item.sku_id,
			tour_date: pricesInfo.value.date,
		}))
	}

	// 分开选择
	if (combotktData.value.tour_date_type === 10) {
		combos = combotktData.value.combo_sale_infos.map((item, index) => ({
			ticket_sku_id: item.sku_id,
			tour_date: mutiplePriceList.value[index].date,
		}))
	}

	const params = {
		items: [
			{
				sku_id: combotktData.value.id,
				combos,
				price_in_cent: pricesInfo.value.price_in_cent,
				quantity: amountOperationRef.value.amount,
				tourists: touristInfoRef.value.touristList.map((item) => ({
					...(tourist_require_name ? { name: item.name } : {}),
					...(tourist_require_mobile ? { mobile: item.mobile } : {}),
					...(tourist_require_id_value ? { id_type: item.id_type, id_number: item.id_value } : {}),
				})),
			},
		],
	}

	if (contact_require_id_value) {
		// params.contact_id_type = contactInfo.id_type
		params.contact_id_type = 10
		params.contact_id_number = contactInfo.id_value
	}

	if (contact_require_name) {
		params.contact_name = contactInfo.name
	}

	if (contact_require_mobile) {
		params.contact_mobile = contactInfo.mobile
	}

	const data = await $createCombotkt({ data: JSON.stringify(params) })

	uni.navigateTo({ url: `/pages/order/pay?stmt_id=${data.id}` })
}, 500)

const getTicketDetail = async () => {
	const data = await $getCombotktDetail(ticketId.value)

	combotktData.value = data

	// 预售票
	if (combotktData.value.sale_type === 20) {
		pricesInfo.value.date = combotktData.value.prices[0].date
		pricesInfo.value.price_in_cent = combotktData.value.prices[0].price_in_cent
	}

	modalShow.value = combotktData.value.booking_notice_switch
}

onLoad((options) => {
	// 处理 options.date 为空字符串
	if (options.date) {
		date.value = options.date.split(",")
	}

	ticketId.value = options.id

	getTicketDetail()
})

onMounted(() => {
	uni.$on("submit-order-popup-visible", handlePopupVisible)
})

onUnmounted(() => {
	uni.$off("submit-order-popup-visible", handlePopupVisible)
})
</script>

<style lang="scss" scoped>
@import "../ticket/index.scss";

.page-container {
	padding-bottom: calc(128rpx + 48rpx);
	padding-bottom: calc(128rpx + 48rpx + env(safe-area-inset-bottom));
}

.card-wrap {
	margin: 24rpx;
}

.card-top {
	display: flex;
	align-items: center;

	.tips {
		margin-left: 8rpx;
		font-size: 24rpx;
		color: #86909c;
		line-height: 34rpx;

		.number {
			color: #bc8400;
		}
	}
}

.title {
	font-weight: 600;
	font-size: 32rpx;
	color: rgba(0, 0, 0, 0.9);
	line-height: 52rpx;
}

.info-block {
	border-bottom: 1rpx solid #f3f3f3;

	&:last-child {
		border-bottom: none;
	}
}

.ticket-info {
	padding-top: 24rpx;

	.display-name-wrap {
		padding-bottom: 32rpx;
		border-bottom: 1rpx solid #f3f3f3;

		.display-name {
			font-weight: 600;
			font-size: 36rpx;
			color: rgba(0, 0, 0, 0.9);
			line-height: 50rpx;
		}
	}

	.prices {
		margin-top: 32rpx;

		.tourist-tip-info {
			display: flex;
			align-items: center;
			margin-bottom: 24rpx;
			padding-left: 24rpx;
			height: 64rpx;
			background: rgba(254, 224, 56, 0.1);
			border-radius: 12rpx;

			.icon {
				width: 28rpx;
				height: 28rpx;
				margin-right: 8rpx;
			}

			.text {
				font-size: 24rpx;
				color: #bc8400;
				line-height: 34rpx;
			}
		}

		.combo_sale_item {
			padding-bottom: 40rpx;

			&:last-child {
				border-bottom: 1rpx solid #f3f3f3;
			}

			.sku_name {
				position: relative;
				padding-left: 18rpx;
				margin-bottom: 28rpx;
				font-weight: 600;
				font-size: 32rpx;
				color: rgba(0, 0, 0, 0.9);
				line-height: 44rpx;

				&::before {
					content: "";
					position: absolute;
					left: 0;
					top: 50%;
					transform: translateY(-50%);
					width: 6rpx;
					height: 24rpx;
					background: #fee038;
					border-radius: 5rpx;
				}
			}
		}
	}

	.sale-labels-wrap {
		margin-top: 24rpx;
	}

	.ops {
		margin-top: 32rpx;
	}
}

.bottom {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100vw;
	height: calc(128rpx + env(safe-area-inset-bottom));
	height: calc(128rpx + constant(safe-area-inset-bottom));
	padding: 24rpx 24rpx calc(24rpx + env(safe-area-inset-bottom));
	background-color: #fff;
	display: flex;
	align-items: center;
	justify-content: space-between;
	z-index: 10;
	box-shadow: inset 0rpx 2rpx 0rpx 0rpx #f1f2f5;

	.price {
		display: flex;
		align-items: baseline;
		color: #fe4f2f;

		.prefix {
			font-size: 28rpx;
			line-height: 36rpx;
		}

		.num {
			font-size: 48rpx;
			line-height: 36rpx;
		}
	}

	.btn {
		width: 320rpx;
		height: 80rpx;
		line-height: 80rpx;
		background: #fee038;
		border-radius: 40rpx;
		font-weight: 600;
		font-size: 28rpx;
		color: #1d2129;
		text-align: center;

		&.disabled {
			background-color: #f6f6f9;
		}
	}
}
</style>
